var mainSwiper;
var doLiulian;


$(function () {
    var playFlag = false;//开始游戏标志
    var yaoCount = 0; //摇动次数
    /**
     * 预加载
     */
    var preload = function () {
        var $list = $("img");
        var index = 0;

        var load = function () {
            if (index < $list.length) {
                var src = $list.eq(index).data("src");
                if (!src) {
                    index++;
                    $("#percent").html(Math.floor(index / $list.length));
                    load();
                    return;
                }
                var img = new Image();
                img.src = src;
                img.onload = img.onerror = function () {
                    $list.eq(index).attr("src", src);
                    index++;
                    $("#percent").html(Math.floor((index / $list.length) * 100));
                    load();
                }
            } else {
                if (hascode == '') {
                    mainSwiper.slideTo(1);
                } else {
                    var imgH = $("#page-4").find(".code img").height();
                    var imgW = $("#page-4").find(".code img").width();
                    var pTop = 0.355 * imgH;
                    var pLeft = imgW * 0.345 + (($("#page-4").find(".code").width() - imgW) / 2);

                    $("#page-4").find(".code .code-id").html(code);
                    $("#page-4").find(".code .code-id").css("top", pTop + "px");
                    $("#page-4").find(".code .code-id").css("left", pLeft + "px");
                    mainSwiper.slideTo(4);
                }
            }
        };

        load();
    };
    /**
     * 开始游戏操作
     */
    var beginGameAction = function () {
        $("#begin-game").on("click", function () {
            mainSwiper.slideTo(2);
        });
    };

    /**
     * 倒计时
     */
    var Countdown = function (cb) {
        $("#page-2").find(".float-time").show();
        $("#page-2").find(".float-time").find(".num")
            .html(3)
            .addClass("anim");
        setTimeout(function () {
            $("#page-2").find(".float-time").find(".num").removeClass("anim");
            setTimeout(function () {
                $("#page-2").find(".float-time").find(".num").html(2)
                    .addClass("anim");
            }, 100);
            setTimeout(function () {
                $("#page-2").find(".float-time").find(".num").removeClass("anim");
                setTimeout(function () {
                    $("#page-2").find(".float-time").find(".num").html(1)
                        .addClass("anim");
                }, 100);
                setTimeout(function () {
                    $("#page-2").find(".float-time").hide();
                    playFlag = true;
                    cb();
                }, 1000);
            }, 1000);
        }, 1000);
    };


    /**
     * 震动
     */
    var zhendong = function () {
        var shake = function () {
            var el = "#page-2 .loudou img.ll-image";
            for (var i = 0; i < $(el).length; i++) {
                var $el = $(el).eq(i);
                var pos = $el.offset();
                if (Math.random() > 0.5) {
                    $el.css('top', pos['top'] + Math.random() * 10 < 10 ? (Math.random() * 10 * (-1)) : Math.random() * 10);
                } else {
                    $el.css('left', pos['left'] + Math.random() * 10 < 10 ? (Math.random() * 10 * (-1)) : Math.random() * 10);
                }
            }
        };

        var doTime = function () {
            shake();
        };

        var time = setInterval(doTime, 30);

        return {
            stop: function () {
                clearInterval(time);
            }
        }
    };
    /**
     * 起点 top 45% left 35%~55%
     * 终点 top 70%~82% left 35%~55%
     */
    doLiulian = function () {
        yaoCount++;
        var index = Math.floor(Math.random() * 5) + 1;
        var html = '<div class="ll ll-' + index + '">' +
            '<img src="./images/p-2/r-' + index + '.png" alt=""/>' +
            '</div>';
        var $el = $(html);
        $("#page-2").append($el);

        var startTop = "45%";
        var startLeft = Math.random() * 41 + 25 + "%";
        var endTop = Math.random() * 13 + 70 + "%";
        $el.css({
            "top": startTop,
            "left": startLeft
        }).show();
        setTimeout(function () {
            $el.animate({
                "top": endTop,
                "left": startLeft,
                "opacity": 0
            }, 1000, "ease-in-out");
        }, 100);

    };

    /**
     * 监听摇一摇事件
     */
    var listenYao = function () {
        var SHAKE_THRESHOLD = 3000;
        var last_update = 0;
        var x = y = z = last_x = last_y = last_z = 0;

        function init() {
            if (window.DeviceMotionEvent) {
                window.addEventListener('devicemotion', deviceMotionHandler, false);
            } else {
                alert('not support mobile event');
            }
        }

        function deviceMotionHandler(eventData) {
            var acceleration = eventData.accelerationIncludingGravity;
            var curTime = new Date().getTime();
            if ((curTime - last_update) > 100) {
                var diffTime = curTime - last_update;
                last_update = curTime;
                x = acceleration.x;
                y = acceleration.y;
                z = acceleration.z;
                var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

                if (speed > SHAKE_THRESHOLD) {
                    if (!playFlag) return;
                    doLiulian();
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }

        init();
    };

    /**
     * 抽奖接口
     */
    var calculate = function () {
        $.ajax({
            url: "data.php",
            type: "post",
            data: "openid=" + openid,
            dataType: "json",
            success: function (data) {
                if (data.success) {
                    var imgH = $("#page-4").find(".code img").height();
                    var imgW = $("#page-4").find(".code img").width();
                    var pTop = 0.355 * imgH;
                    var pLeft = imgW * 0.345 + (($("#page-4").find(".code").width() - imgW) / 2);

                    $("#page-4").find(".code .code-id").html(data.id);
                    $("#page-4").find(".code .code-id").css("top", pTop + "px");
                    $("#page-4").find(".code .code-id").css("left", pLeft + "px");
                    title_type = 1;
                    mainSwiper.slideTo(4);
                } else {
                    mainSwiper.slideTo(3);
                }
            },
            error: function () {
                mainSwiper.slideTo(3);
            }
        })
    };

    /**
     * 摇一摇
     * @param tc
     */
    var yaoyao = function (tc) {
        setTimeout(function () {
            playFlag = false;
            tc.stop();
            if (yaoCount > 40) {
                calculate();
            } else {
                mainSwiper.slideTo(3);
            }
        }, 10 * 1000);

        setTimeout(function () {
            var music = document.getElementById("music");
            var bool = !music.played || music.paused || music.ended;
            if (bool) {
                music.play();
            }
            music.play();
        }, 9500);
    };

    /**
     * 分享处理
     */
    var shareDialog = function () {
        $("#page-3,#page-4").find(".invite").on("click", function () {
            $(this).parents(".swiper-slide").find(".share").show();
        });
        $("#page-3,#page-4").find(".share").on("click", function () {
            $(this).hide();
        });
        $("#page-3,#page-4").find(".again").on("click", function () {
            mainSwiper.slideTo(1);
        });
    };

    var wxShare = function () {

        /* wx.config(wxconfig);
         wx.ready(function () {
         wx.onMenuShareTimeline(shareDate);
         wx.onMenuShareAppMessage(shareDate);
         }); */
    };

    mainSwiper = new Swiper('#main-container', {
        direction: 'vertical',
        loop: false,
        effect: 'fade',
        initialSlide: 0,
        noSwiping: true,
        watchSlidesProgress: true,
        onSlideChangeEnd: function (swiper) {
            swiperAnimate(swiper); //每个slide切换结束时也运行当前slide动画
            if (swiper.activeIndex == 1) {
            }
            if (swiper.activeIndex == 2) {
                yaoCount = 0;
                Countdown(function () {
                    var tc = zhendong();
                    yaoyao(tc);
                });
            }
            if (swiper.activeIndex == 3) {
                if (yaoCount <= 30) {
                    $("#page-3").find(".desc").addClass("d-1");
                } else if (yaoCount > 30 && yaoCount <= 60) {
                    $("#page-3").find(".desc").addClass("d-3");
                } else {
                    $("#page-3").find(".desc").addClass("d-5");
                }
            }

            if (swiper.activeIndex == 4) {
                share_timeline_data = {
                    'title': '离免费榴莲多多比萨，只有一步之“摇”，你也来挑战？',
                    'callbackfunc': function () {

                    }
                };

                share_app_data = {
                    'title': '离免费榴莲多多比萨，只有一步之“摇”，你也来挑战？',
                    'desc': '离免费榴莲多多比萨，只有一步之“摇”，你也来挑战？',
                    'callbackfunc': function () {

                    }
                };
            }

        },
        onInit: function (swiper) {
            wxShare();
            swiperAnimateCache(swiper); //隐藏动画元素
            swiperAnimate(swiper); //初始化完成开始动画
            listenYao();
            preload();
            beginGameAction();
            shareDialog();
        }
    });
});
